package wetalk.software.bupt.com.wetalk.view.activity;

/**
 * Created by whc07 on 2017/12/23.
 */

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.po.ChatUser;
import wetalk.software.bupt.com.wetalk.model.po.Group;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.util.DensityUtil;
import wetalk.software.bupt.com.wetalk.util.PinYinUtil;
import wetalk.software.bupt.com.wetalk.util.PinyinComparator;
import wetalk.software.bupt.com.wetalk.util.ViewHolder;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.widget.AddGroupSideBar;

import static android.content.ContentValues.TAG;

public class AddGroupChatActivity extends BaseActivity implements
        OnClickListener, OnItemClickListener {
    private ImageView iv_search, img_back;
    private TextView tv_header, txt_title, txt_right;;
    private ListView listView;
    private EditText et_search;
    private AddGroupSideBar indexBar;
    private TextView mDialogText;
    private WindowManager mWindowManager;
    /** 是否为一个新建的群组 */
    protected boolean isCreatingNewGroup;
    /** 是否为单选 */
    private boolean isSignleChecked;
    private ContactAdapter contactAdapter;
    /** group中一开始就有的成员 */
    //jjj111
    private List<String> exitingMembers = new ArrayList<String>();
    private List<String> exitingMembersId = new ArrayList<String>();
    private List<User> alluserList;// 好友列表
    // 可滑动的显示选中用户的View
    private LinearLayout menuLinerLayout;

    // 选中用户总数,右上角显示
    int total = 0;
    private String userId = null;
    private String groupId = null;
    private String groupname;
    // 添加的列表
    private List<String> addList = new ArrayList<String>();
    private List<String> addListId = new ArrayList<String>();
    private String hxid;
    private Group group;
    //activity变量

    private IntentFilter intentFilter;
    private IntentFilter intentFilter1;
    private AndroidClientService.SendBinder sendBinder;
    private  AddGroupReceiver addGroupReceiver;
    private PullMemberReceiver pullMemberReceiver;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    ChatUser currentUser  = UserManager.getInstance(AddGroupChatActivity.this).getCurrentUser();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_chatroom);
        super.onCreate(savedInstanceState);
        initGroupBC();
        initControl();
        initView();
        initData();
        setListener();
        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);
        intentFilter=new IntentFilter("return_addGroup");
        addGroupReceiver =new AddGroupReceiver();
        registerReceiver(addGroupReceiver,intentFilter);

    }



    protected void initControl() {
        txt_title = (TextView) findViewById(R.id.txt_title);
        txt_title.setText("发起群聊");
        txt_right = (TextView) this.findViewById(R.id.txt_right);
        txt_right.setText("确定");
        txt_right.setTextColor(0xFF45C01A);
        img_back = (ImageView) findViewById(R.id.img_back);
        img_back.setVisibility(View.VISIBLE);
        menuLinerLayout = (LinearLayout) this
                .findViewById(R.id.linearLayoutMenu);
        et_search = (EditText) this.findViewById(R.id.et_search);
        listView = (ListView) findViewById(R.id.list);
        iv_search = (ImageView) this.findViewById(R.id.iv_search);
        mDialogText = (TextView) LayoutInflater.from(this).inflate(
                R.layout.list_position, null);
        mDialogText.setVisibility(View.INVISIBLE);
        indexBar = (AddGroupSideBar) findViewById(R.id.sideBar);
        indexBar.setListView(listView);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        mWindowManager.addView(mDialogText, lp);
        indexBar.setTextView(mDialogText);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View headerView = layoutInflater.inflate(R.layout.item_chatroom_header,
                null);
        tv_header = (TextView) headerView.findViewById(R.id.tv_header);
        listView.addHeaderView(headerView);
        listView.setOnItemClickListener(this);
    }


    protected void initView() {
        //hxid = Utils.getValue(AddGroupChatActivity.this, Constants.User_ID);
        Intent intent = getIntent();
        groupName = intent.getStringExtra("GROUP_ID");//// TODO: 2018/2/28
        userId = intent.getStringExtra("User_ID");
        if (groupName != null) {
            isCreatingNewGroup = false;
            group = WeTalkDB.create(AddGroupChatActivity.this).queryGroupByName(groupName);
            if (groupName != null) {
                String[] array = group.getUser_id().split("、");
                for (int i=0;i<array.length;i++){
                    User user = WeTalkDB.create(AddGroupChatActivity.this).queryUserByid(array[i]);
                    exitingMembers.add(user.getUserName());
                }
                groupId = group.getGroup_id();
            }
        }
        else
        if (userId != null) {
            isCreatingNewGroup = true;
            exitingMembers.add(userId);
            total = 1;
            addList.add(userId);
        } else {
            isCreatingNewGroup = true;
        }
    }

    public static final String getValue(Context context, String key) {
        return getSharedPreference(context).getString(key, "");
    }

    private static final SharedPreferences getSharedPreference(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context);
    }



    protected void initData() {
        // 获取好友列表
        alluserList = new ArrayList<User>();
        this.alluserList= WeTalkDB.create(AddGroupChatActivity.this).queryUserList();
        Collections.sort(alluserList,new PinyinComparator());
        contactAdapter = new ContactAdapter(AddGroupChatActivity.this, alluserList);
        listView.setAdapter(contactAdapter);
        // Toast.makeText(AddGroupChatActivity.this,alluserList.size(),Toast.LENGTH_LONG).show();
    }



    protected void setListener() {
        img_back.setOnClickListener(this);
        tv_header.setOnClickListener(this);
        txt_right.setOnClickListener(this);
        et_search.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.length() > 0) {
                    String str_s = et_search.getText().toString().trim();
                    List<User> users_temp = new ArrayList<User>();
                    for (User user : alluserList) {
                        String usernick = user.getUserName();
                        if (usernick.contains(str_s)) {
                            users_temp.add(user);
                        }
                        contactAdapter = new ContactAdapter(AddGroupChatActivity.this, users_temp);
                        listView.setAdapter(contactAdapter);
                    }
                    //total=users_temp.size();
                } else {
                    contactAdapter = new ContactAdapter(AddGroupChatActivity.this, alluserList);
                    listView.setAdapter(contactAdapter);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                AddGroupChatActivity.this.finish();
                AddGroupChatActivity.this.overridePendingTransition(R.anim.push_right_in,
                        R.anim.push_right_out);
                break;
            case R.id.tv_header:

                Intent intent = new Intent(AddGroupChatActivity.this,GroupListActivity.class);
                startActivity(intent);
                // TODO 打开群列表
                break;
            case R.id.txt_right:// 确定按钮
                save();
                break;
            default:
                break;
        }
    }

    /**
     * 确认选择的members
     *
     * @param
     */
    @RequiresApi(api = Build.VERSION_CODES.ECLAIR)
    public void save() {
        if (addList.size() == 0) {
            Toast.makeText(AddGroupChatActivity.this, "请选择用户", Toast.LENGTH_LONG).show();
            return;
        }
        // 如果只有一个用户说明只是单聊,并且不是从群组加人
        if (addList.size() == 1 && isCreatingNewGroup) {

            String userId = addList.get(0);
            User user=WeTalkDB.create(AddGroupChatActivity.this).queryFriendByName(userId);
            UserInfoActivity.actionStart(AddGroupChatActivity.this,user,"look");
        } else {
            if (isCreatingNewGroup) {
                Toast.makeText(AddGroupChatActivity.this,"正在创建群聊...",Toast.LENGTH_LONG).show();//// TODO: 2018/2/28
                createNewGroup(addList);// 创建群组
                //getLoadingDialog("正在创建群聊...").show();
            } else {
                Toast.makeText(AddGroupChatActivity.this,"正在加人...",Toast.LENGTH_LONG).show();//// TODO: 2018/2/28
                //getLoadingDialog("正在加人...").show();

                for (int i =0;i<exitingMembers.size();i++){
                    User user=WeTalkDB.create(AddGroupChatActivity.this).queryFriendByName(exitingMembers.get(i));
                    exitingMembersId.add(user.getUserID());
                }
                for (int i =0;i<addList.size();i++){
                    User user=WeTalkDB.create(AddGroupChatActivity.this).queryFriendByName(addList.get(i));
                    addListId.add(user.getUserID());
                }

                String user_Id = StringUtils.join(exitingMembersId, "、")+"、"+StringUtils.join(addListId,"、");
                //for (String m:addListId) {
                    pullMember(groupId, user_Id, new PushListener() {
                        @Override
                        public void onSuccess() {
                            Toast.makeText(AddGroupChatActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(int var1, String var2) {
                            Toast.makeText(AddGroupChatActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                //}
            }

        }
    }

    class ContactAdapter extends BaseAdapter implements SectionIndexer {
        private Context mContext;
        private boolean[] isCheckedArray;
        private Bitmap[] bitmaps;
        private List<User> list = new ArrayList<User>();

        @SuppressWarnings("unchecked")
        public ContactAdapter(Context mContext, List<User> users) {
            this.mContext = mContext;
            this.list = users;
            bitmaps = new Bitmap[list.size()];
            isCheckedArray = new boolean[list.size()];
            // 排序(实现了中英文混排)
            Collections.sort(list, new PinyinComparator());
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            final User user = list.get(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(
                        R.layout.contact_item, null);
            }
            ImageView ivAvatar = ViewHolder.get(convertView,
                    R.id.contactitem_avatar_iv);
            TextView tvCatalog = ViewHolder.get(convertView,
                    R.id.contactitem_catalog);
            TextView tvNick = ViewHolder
                    .get(convertView, R.id.contactitem_nick);
            final CheckBox checkBox = ViewHolder
                    .get(convertView, R.id.checkbox);
            checkBox.setVisibility(View.VISIBLE);
            String catalog = PinYinUtil.converterToFirstSpell(
                    user.getUserName()).substring(0, 1);
            if (position == 0) {
                tvCatalog.setVisibility(View.VISIBLE);
                tvCatalog.setText(catalog);
            } else {
                User Nextuser = list.get(position - 1);
                String lastCatalog = PinYinUtil.converterToFirstSpell(
                        Nextuser.getUserName()).substring(0, 1);
                if (catalog.equals(lastCatalog)) {
                    tvCatalog.setVisibility(View.GONE);
                } else {
                    tvCatalog.setVisibility(View.VISIBLE);
                    tvCatalog.setText(catalog);
                }
            }
            ivAvatar.setImageResource(R.drawable.head);
            tvNick.setText(user.getUserName());

          

                checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // 群组中原来的成员一直设为选中状态
                        if (exitingMembers.contains(user.getUserName())) {
                            isChecked = true;
                            checkBox.setChecked(true);
                        }
                        isCheckedArray[position] = isChecked;
                        // 如果是单选模式
                        if (isSignleChecked && isChecked) {
                            for (int i = 0; i < isCheckedArray.length; i++) {
                                if (i != position) {
                                    isCheckedArray[i] = false;
                                }
                            }
                            contactAdapter.notifyDataSetChanged();
                        }

                        if (isChecked) {
                            // 选中用户显示在滑动栏显示
                            showCheckImage(null, list.get(position));
                        } else {
                            // 用户显示在滑动栏删除
                            deleteImage(list.get(position));
                        }
                    }
                });
                // 群组中原来的成员一直设为选中状态
                if (exitingMembers.contains(user.getUserName())) {
                    checkBox.setChecked(true);
                    isCheckedArray[position] = true;
                } else {
                    checkBox.setChecked(isCheckedArray[position]);
                }

            return convertView;
        }

        @Override
        public int getPositionForSection(int section) {
            for (int i = 0; i < list.size(); i++) {
                User user = list.get(i);
                String l = PinYinUtil
                        .converterToFirstSpell(user.getUserName()).substring(0,
                                1);
                char firstChar = l.toUpperCase().charAt(0);
                if (firstChar == section) {
                    return i;
                }
            }
            return 0;
        }

        @Override
        public int getSectionForPosition(int position) {
            return 0;
        }

        @Override
        public Object[] getSections() {
            return null;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
        CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
        checkBox.toggle();
    }

    // 即时显示被选中用户的头像和昵称。
    private void showCheckImage(Bitmap bitmap, User glufineid) {
        if (exitingMembers.contains(glufineid.getUserName()) && groupId != null) {
            return;
        }
        if (addList.contains(glufineid.getUserName())) {
            return;
        }

        final ImageView imageView = new ImageView(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                DensityUtil.dip2px(this, 40), DensityUtil.dip2px(this, 40));
        lp.setMargins(0, 0, DensityUtil.dip2px(this, 5), 0);
        imageView.setLayoutParams(lp);

        // 设置id，方便后面删除
        imageView.setTag(glufineid);
        if (bitmap == null) {
            imageView.setImageResource(R.drawable.head);
        } else {
            imageView.setImageBitmap(bitmap);
        }

        menuLinerLayout.addView(imageView);
        //txt_right.setText("确定(" + total + ")");
        if (total > 0) {
            if (iv_search.getVisibility() == View.VISIBLE) {
                iv_search.setVisibility(View.GONE);
            }
        }
        addList.add(glufineid.getUserName());
    }

    private void deleteImage(User glufineid) {
        View view = (View) menuLinerLayout.findViewWithTag(glufineid);

        menuLinerLayout.removeView(view);
        //total--;
        //txt_right.setText("确定(" + total + ")");
        addList.remove(glufineid.getUserName());
        if (total < 1) {
            if (iv_search.getVisibility() == View.GONE) {
                iv_search.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 创建新群组
     *
     * @param newmembers
     */
    String groupName = "";
    String manber = "";
    String user_id="";

    private void createNewGroup(final List<String> members) {

        user_id=members.get(0);

        for (int i = 1;i<members.size();i++){
            user_id= user_id+"、"+members.get(i);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建群组方法
                try {
                    final String[] strmembers = new String[members.size()];
                    //groupId = createGroupName();//uuid生成唯一群id
                    manber=currentUser.getUserID();
                    for (int i = 0; i < members.size(); i++) {
                        User user = WeTalkDB.create(AddGroupChatActivity.this).queryFriendByName(members.get(i));
                        if (user != null) {

                            manber=manber+"、"+user.getUserID();

                            if (i < 3) {
                                if (i == 0)
                                    groupName = user.getUserName();
                                else
                                    groupName += "," + user.getUserName();
                            } else if (i == 4) {
                                groupName += "...";
                            }
//                            strmembers[i] = user.getUserID();
//                            if (i == 0) {
//                                manber = user.getUserID();
//                            } else {
//                                manber += "、" + user.getUserID();
//                            }
                        }
                    }

                    final Group group = new Group(groupName,manber);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            if (group != null) {
                                // TODO 保存本地数据库
                                //WeTalkDB.create(AddGroupChatActivity.this).addGroup(group);
                                addServieGroup(groupName,manber, new PushListener(){
                                    @Override
                                    public void onSuccess() {
                                        Toast.makeText(AddGroupChatActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onFailure(int var1, String var2) {
                                        Toast.makeText(AddGroupChatActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                                    }
                                });

                            }
                        }

                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(AddGroupChatActivity.this, "创建失败", Toast.LENGTH_SHORT).show();
                            //getLoadingDialog("正在创建群聊...").dismiss();
                        }
                    });
                }

            }
        }).start();
    }

    private void pullMember(String id,String user_id, final PushListener pushCallback ){//TODO
        final String targetId = "sys_group";
        final String userId= UserManager.getInstance(AddGroupChatActivity.this).getCurrentUser().getUserID();
        final JSONObject json=new JSONObject();
        String[]M= id.split("_");
        try {
            json.put("uid",currentUser.getUserID());
            json.put("gid",M[0]);
            json.put("mid",user_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"pullMember",bs);

                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();


    }

    private void addServieGroup(String name,String user_id ,final PushListener pushCallback)  {
        final String targetId = "sys_group";
        final String userId= UserManager.getInstance(AddGroupChatActivity.this).getCurrentUser().getUserID();
        final JSONObject json=new JSONObject();
        try {
            json.put("uid",currentUser.getUserID());//新更改
//            json.put("gid",id);
            json.put("gname",name);
            json.put("mem",user_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {

                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"createGroup",bs);

                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();

    }
    //注册广播接收器
    private void initGroupBC(){
        //接收广播
        intentFilter=new IntentFilter(WeTalkConfig.BROADCAST_CREATE_GROUP);
        addGroupReceiver=new AddGroupReceiver();
        registerReceiver(addGroupReceiver,intentFilter);
        intentFilter1=new IntentFilter(WeTalkConfig.BROADCAST_PULL_MEMBER_GROUP);
        pullMemberReceiver= new PullMemberReceiver();
        registerReceiver(pullMemberReceiver,intentFilter1);

    }




    private class AddGroupReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content=intent.getStringExtra("result");

            // 收到这个广播的时候，message已经在消息表中，可直接获取
            try {
                JSONObject json=new JSONObject(content);
//                String group_id = "111";
//                String group_name = "222";
//                String user_id = "1、3、5";


                String group_id = json.getString("gid")+"_g";
                String group_name = json.getString("gname");
                String user_id = json.getString("mem");
                Group group = new Group(group_id,group_name,user_id);
                WeTalkDB.create(AddGroupChatActivity.this).addGroup(group);
                Toast.makeText(context, "创建群组"+group_name+"成功", Toast.LENGTH_SHORT).show();
                Intent intent1=new Intent(AddGroupChatActivity.this,GroupSettingActivity.class);
                intent1.putExtra("groupname",group_name);
                startActivity(intent1);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 广播终结
            abortBroadcast();
            finish();

        }

    }

    private class PullMemberReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content=intent.getStringExtra("result");

            // 收到这个广播的时候，message已经在消息表中，可直接获取
            try {
                JSONObject json=new JSONObject(content);
                String group_id = json.getString("gid")+"_g";
                String uname = json.getString("uname");
                String user_name = json.getString("mname");
                String[] usernames = user_name.split("、");
                Group group=WeTalkDB.create(AddGroupChatActivity.this).queryGroupByID(group_id);
//                String[] member=group.getUser_id().split("、");
//                String[] members = new String[member.length+1];
//
//
//                for (int i = 0;i<member.length;i++){
//                    members[i]=member[i];
//                }
//
//                //User user = WeTalkDB.create(AddGroupChatActivity.this).queryUserByName(user_name);
//                members[member.length]=WeTalkDB.create(AddGroupChatActivity.this).queryUserByName(usernames[0]).getUserID();
//                String groupMemberListString = members[0];
//                for (String m:members){
//                    if (m.equals(members[0])){
//                        continue;
//                    }
//                    groupMemberListString=groupMemberListString+"、"+m;
//
//                }
//                //String userid = StringUtils.join(members);
//                System.out.println(groupMemberListString);
//                group.setUser_id(groupMemberListString);
                String[] userName = user_name.split("、");
                String[] user_id = new String[userName.length];
                for (int i = 0;i<userName.length;i++){
                    String userid = WeTalkDB.create(AddGroupChatActivity.this).queryUserByName(userName[i]).getUserID();
                    user_id[i] = userid;
                }
                String user_ids = StringUtils.join(user_id,"、");
                group.setUser_id(user_ids);
                WeTalkDB.create(AddGroupChatActivity.this).modifyGroupInfo(group);
                Toast.makeText(context, "群组添加成员成功", Toast.LENGTH_SHORT).show();
                Intent intent1=new Intent(AddGroupChatActivity.this,GroupSettingActivity.class);
                intent1.putExtra("groupname",group.getGroup_name());
                startActivity(intent1);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 广播终结
            //abortBroadcast();
            finish();

        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(addGroupReceiver);
        unbindService(connection);
    }
}